﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace LinkingCloud.API.Common
{
    public static class ListConvert<T>
    {
        public static string ListToCsv(List<T> list, string fileName, out string msg)
        {
            msg = "";
            try
            {
                //Directory.GetCurrentDirectory() 获取项目的根文件夹，就是当前项目路径（这个我之前没有加，用的相对路径，系统匹配的路径写法不对，所以会报错）
                //@"\File\" 我在项目下建的文件夹，注意用反斜杠
                //DateTime.Now.ToString("yyyyMMdd") 今天日期
                string filePath = Directory.GetCurrentDirectory() + @"\File\" + DateTime.Now.ToString("yyyyMMdd"); //文件路径

                //如果没有这个文件夹就创建
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                //检查实体集合不能为空
                if (list == null || list.Count < 1)
                {
                    throw new Exception("需转换的集合为空");
                }
                //取出第一个实体的所有Propertie
                Type entityType = list[0].GetType();
                PropertyInfo[] entityProperties = entityType.GetProperties();
                StringBuilder strRows = new StringBuilder();
                //Header
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    strRows.Append("\"" + entityProperties[i].Name + "\"");
                    if (entityProperties.Length > 1 && i != entityProperties.Length - 1)
                    {
                        strRows.Append(",");
                    }
                }
                strRows.Append("\r\n");//换行

                StringBuilder body = new StringBuilder();
                //Body
                string value = "";
                string str = "";
                int n = 1;
                foreach (var item in list)
                {
                    foreach (var nameList in item.GetType().GetProperties())
                    {
                        value = nameList.GetValue(item, null) != null ? nameList.GetValue(item, null).ToString() : "";
                        if (!string.IsNullOrEmpty(value))
                        {
                            if (value.IndexOf("\"") != -1)
                            {
                                value = value.Replace("\"", "\"\"");
                            }
                            body.Append(",\"" + value + "\"");
                        }
                        else
                        {
                            body.Append("," + nameList.GetValue(item, null));
                        }
                    }
                    body.Append("\r\n");//换行
                    str = body.ToString().Substring(1);
                    if (n == list.Count)
                    {
                        str = str.Substring(0, str.LastIndexOf("\r\n"));
                    }
                    strRows.Append(str);
                    body = new StringBuilder();
                    n++;
                }
                string sExportFileName = fileName + ".csv"; //文件名
                string path = filePath + "\\" + sExportFileName;
                //检查是否有这个文件，没有创建文件，最后一定要Close，不然文件占用无法写入
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                }
                //写入文件
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
                {
                    file.Write(strRows);
                    file.Dispose();
                }
                return path;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return null;
            }
        }

        public static string ListToTxt(List<T> list, string fileName,out string msg)
        {
            msg = "";
            try
            {
                //Directory.GetCurrentDirectory() 获取项目的根文件夹，就是当前项目路径（这个我之前没有加，用的相对路径，系统匹配的路径写法不对，所以会报错）
                //@"\File\" 我在项目下建的文件夹，注意用反斜杠
                //DateTime.Now.ToString("yyyyMMdd") 今天日期
                string filePath = Directory.GetCurrentDirectory() + @"\File\" + DateTime.Now.ToString("yyyyMMdd"); //文件路径

                //如果没有这个文件夹就创建
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                //检查实体集合不能为空
                if (list == null || list.Count < 1)
                {
                    throw new Exception("需转换的集合为空");
                }
                //取出第一个实体的所有Propertie
                Type entityType = list[0].GetType();
                PropertyInfo[] entityProperties = entityType.GetProperties();
                StringBuilder strRows = new StringBuilder();
                StringBuilder body = new StringBuilder();
                //Body
                string value = "";
                string str = "";
                int i = 1;
                foreach (var item in list)
                {
                    foreach (var nameList in item.GetType().GetProperties())
                    {
                        value = nameList.GetValue(item, null) != null ? nameList.GetValue(item, null).ToString() : "";
                        if (!string.IsNullOrEmpty(value))
                        {

                            body.Append("," + value);
                        }
                        else
                        {
                            body.Append("," + nameList.GetValue(item, null));
                        }
                    }
                    body.Append("\r\n");//换行
                    str = body.ToString().Substring(1);
                    if (i == list.Count)
                    {
                        str = str.Substring(0, str.LastIndexOf("\r\n"));
                    }
                    strRows.Append(str);
                    body = new StringBuilder();
                    i++;
                }

                string sExportFileName = fileName + ".txt"; //文件名
                string path = filePath + "\\" + sExportFileName;
                //检查是否有这个文件，没有创建文件，最后一定要Close，不然文件占用无法写入
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                }
                //写入文件
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
                {
                    file.Write(strRows);
                    file.Dispose();
                }
                return path;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return null;
            }
        }
    }
}
